// 帐号管理

use actix_web::{web, post, error::ResponseError, get};
use sea_orm::{EntityTrait, QuerySelect, QueryFilter, ColumnTrait};
use serde::Deserialize;
use crate::{tool_bag::*, app_start::app_states::state_verification_code::MVerCodeEmail};
use lettre::Address;
use derive_more::{Display, Error};

pub fn controller_config(cfg: &mut web::ServiceConfig) {
	// cfg.configure(api_test::controller_config);
	cfg.service(
		web::scope("/account_manage")
			.service(account_login_0)	
	);
}

// struct Str(String);


//<<< 帐号注册

/// 邮箱是否存在 
/// -> Some(v):存在
async fn sql_is_email_exist(email:&Address)->Option<table::用_户_帐_号_信_息_表::Model>{
	let data = entity_table::用户帐号信息表::find()
		.column(table::用_户_帐_号_信_息_表::Column::Id)
		.filter(Condition::all()
			.add(table::用_户_帐_号_信_息_表::Column::邮箱.eq(email.to_string()))
		).one(*MYSQL_DB).await.unwrap();
	data
}

#[derive(Debug, Display)]
enum AccountLoginError {

	#[display(fmt = "email格式不正确:{{email:{}}}", _0)]
	/// .0: email
	EmailFormatIncorrect(String),
	#[display(fmt = "邮箱发送失败")]
	EmailSendFail,
	#[display(fmt = "邮箱已注册,不可重复注册")]
	EmailAlreadyExist,
	#[display(fmt = "注册码以过期")]
	CodeExpired ,
	#[display(fmt = "注册码不匹配")]
	CodeNotMatch

}
impl ResponseError for AccountLoginError { }

#[derive(Deserialize)]
struct AccountLogin {// ! 前端应该统一使用它,就算其他属性用不到,也得加上
    email: String,//邮箱
	code: String ,//注册码
	name: String ,//昵称
	password:String,//密码
	//<< 未来加入
}

#[post("/account_login_0")]
async fn account_login_0(json:web::Json<AccountLogin>,state:web::Data<MVerCodeEmail>)->Result<&'static str,AccountLoginError>{
	let web::Json(AccountLogin { email ,..}) = json;
	//验证邮箱格式
	let adress:Address = match email.clone().try_into(){
		Ok(v) => v,
		Err(e) => return Err(AccountLoginError::EmailFormatIncorrect(email)),
	};
	let mut state = state.lock().await;

	// 验证邮箱是否存在
	match  sql_is_email_exist(&adress).await {
		Some(v) => (),
		None => return Err(AccountLoginError::EmailAlreadyExist),
	}
	//获取验证码
	let code = state.insert_6(adress.clone().into());
	//生成模板
	let template = html_template::account_login_code::account_login_code(
		&html_template::account_login_code::AccountLoginCode{code}).await;
	//发送邮箱
		match Email::build()
		.subject("Free-Acccount-Login")
		.to(vec![adress])
		.body(EmailBody::Html(template))
		.send(){
			Ok(v) => (),
			Err(e) => return Err(AccountLoginError::EmailSendFail),
		};
	Ok("Ok")
}

#[post("/account_login_1")]
async fn account_login_1(json:web::Json<AccountLogin>,state:web::Data<MVerCodeEmail>)->Result<&'static str,AccountLoginError>{
	let web::Json(AccountLogin { email ,code,name,password,..}) = json;
	//验证邮箱格式
	let adress:Address = match email.clone().try_into(){
		Ok(v) => v,
		Err(e) => return Err(AccountLoginError::EmailFormatIncorrect(email)),
	};
	let mut state = state.lock().await;
	// 查找注册码
	let trualy_code = match state.get(&adress.clone().into()) {
		Some(v) => v,
		None => return Err(AccountLoginError::CodeExpired), 
	};
	// 验证注册码是否相等
	if !code.eq(trualy_code) {
		return Err(AccountLoginError::CodeNotMatch);
	}
	//<< 检查password是否符合格式

	//开始注册
	mysql业务::account_login::affair_begin_login(email,name,password).await;

	Ok("Ok")
}

//<<< end

//<< 设置基础信息

//<< 帐号注销 , 未来后后写



